﻿/**************************************************
	*                      Main
**************************************************/
$(function () {
	
    // Declare global configurations
    $.configGlobal = {
        // Uri api fields
        uriGetMotelsAPI: "http://localhost:1790/motelmaps/all_address",
        urtGetWardsAPI: "http://localhost:1790/motelmaps/all_wards/{0}",
        urtGetDistrictsAPI: "http://localhost:1790/motelmaps/all_districts",
        urlGetResultSearchAPI: "http://localhost:1790/motelmaps/re_search/{0}/{1}",
        urlDeleteMotelsAPI: "http://localhost:1790/motelmaps/delete_address/{0}",
        uriGetAllFriendAPI: "http://localhost:1790/motelmaps/all_friend/{0}",
        uriGetAllRequestFriendAPI: "http://localhost:1790/motelmaps/request_makefriend/{0}",
        uriSendRequestFriendAPI: "http://localhost:1790/motelmaps/send_requestfriend",
        uriDeleteFriendAPI: "http://localhost:1790/motelmaps/delete_friend/{0}",
        uriAgreeMakeFriendAPI: "http://localhost:1790/motelmaps/agree_makefriend",
        uriGetNameAccAPI: "http://localhost:1790/motelmaps/getname/{0}",
        uriSearchFriendAPI: "http://localhost:1790/motelmaps/get_resutlsearch/{0}/{1}",
        // Protocol call
        protoGET: "GET",
        protoPOST: "POST",
        protoDELETE: "DELETE",
        protoPUT: "PUT",
        // Expected datatype
        dataJSON: "json",
        // ContentType
        ctnJSON: "application/json; charset=utf-8",
        // Html fields
        divContainMap: "map_canvas",
        divLeftMenu: ".detail",
        cbWardSearch: "#cbWardSearchAddress",
        cbWardAdd: "#cbWardAddress",
        cbDistrictSearch: "#cbDistrictSearchAddress",
        cbDistrictAdd: "#cbDistrictAddress",
        btnSearch: "#btnsearch",
        btnSave: "#btnSave",
        btnCancel: "#btnCancel",
        btnShareLocation: ".shareLocation",
        msgAddResponse: "#msgAddAddress",
        btnShowAllMotels: "#btnShow",
        btnClearLeftMenu: "#clMarker",
        tabAllFriend: "#tabshowallfriend",
        tabReqFriend: "#tabshowrequestfriend",
        tabFindFriend: "#tabfindfriend",
        email: "#emailds",
        // Variabel fields		
        isFireSelected: false,
        currentMarker: "",
        infoWindow: new google.maps.InfoWindow(),
        menuContext: "",
        currentPointer: "",
        visibleStatus: 1,
        disableStatus: 0,
        mapDiv: "",
        mapObject: "",
        defaultLocaltion: [10.7633174, 106.6823476],
        defaultZoom: 13,
        defaultScaleControl: true,
        districts: "",
        wardsSearch: "",
        wardsAdd: "",
        motels: "",
        addsSearch: "",
        AllFriend: "",
        typerequire: ""
		
	};
	
    var $map = $('#map_canvas'),
	menu = new Menu($map),
	currentPointer;
	
    // Menu item 01
    menu.add('Add new place', 'itemB', addNewMarker);
	
    $.configGlobal.mapObject = $map;
    $.configGlobal.menuContext = menu;
    $.configGlobal.currentPointer = currentPointer;
	
    // Load Districts ComboBox for search & add form 
    getDistrictsComboBoxes();
	
    // Load default map
    RetrievePlaces();
	
    // Add selected index changing to     
    $($.configGlobal.cbDistrictSearch).change(cbDistrictSearchSelectedIndexChanging);
	
    // Add selected index changing to combobox in add form
    $($.configGlobal.cbDistrictAdd).change(cbDistrictAddSelectedIndexChanging);
	
    // Implement click event of search button
    $($.configGlobal.btnSearch).click(btnSearchClick);
	
    // Implement event for btnSave in add form
    $($.configGlobal.btnSave).click(btnSaveOnClick);
	
    // Implement event for btnShowAll 
    $($.configGlobal.btnShowAllMotels).click(btnShowAllOnClick);
	
    // Implement event for btnShareLocation
    $($.configGlobal.btnShareLocation).click(btnShareLocation);
	
    // Show manage friends	
    // $('#danhsachban').click(btnshowfriendonClick);
    // btnshowfriendonClick();
	
    // Hien thi loi moi ket ban
    // $('#loimoiketban').click(btnmakefriendonClick);
	
    // Hien thi tim kiem ban
    // $('#timkiemban').click(btnfindfriendonClick);
	
    // Config popup manage friends
    // $('.fbManageFriend').fancybox();
	
    // Set default state for districts combobox
    setDefaultStateCombobox();
});
//******************************************
// Success! Set a marker on the Google map to show the user's location
//******************************************
function showPositionOnMap(position) {
	var $map = $.configGlobal.mapObject;
	$map.gmap3({
		action: 'addMarker',
		latLng: [position.coords.latitude, position.coords.longitude],
		options: {
			draggable: true
		},
		infowindow: {
			options: {
				content: 'My Place'
			}
		}
	});
}
// Boo! Couldn't obtain the user's location. Translate the error code into something useful and inform the user.
function errorMessage(error) {
	var errors = {
		1: 'Permission denied',
		2: 'Position unavailable',
		3: 'Request timeout'
	};
	alert("Error: " + errors[error.code]);
}
//******************************************
// Declare function to share current user location
//******************************************
function btnShareLocation() {
	// If this browser supports Geolocation, then attempt to obtain the user's location
	if (navigator.geolocation) {
		var timeoutVal = 10 * 1000 * 1000;
		navigator.geolocation.getCurrentPosition(showPositionOnMap, errorMessage, { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 });
	}
	// Geolocation is not supported, inform the user
	else {
		alert("Geolocation is not supported by this browser");
	}
}

//******************************************
// Declare function to set state for components
//******************************************
function setDefaultStateCombobox() {
	var tempDistrictSearchCombo = $($.configGlobal.cbDistrictSearch);
}
//******************************************
// Declare function to clear left menu
//******************************************
function btnClearLeftMenuOnClick() {
	var $map = $.configGlobal.mapObject,
	leftmenu = $.configGlobal.divLeftMenu;
	$(leftMenu).html('');
	// Clear info window
	$map.gmap3({ action: 'clear', name: 'infowindow' });
}
//******************************************
// Declare function to show all address
//******************************************
function btnShowAllOnClick() {
	// Refresh default map
	RetrievePlaces();
	return false;
}
//******************************************
// Declare function to refresh map with current selected value of comboboxes
//******************************************
function refreshMapWithCurrentComboBox() {
	// Get selected district
	var selectedDistrict = $($.configGlobal.cbDistrictSearch).val();
	// Get selected ward
	var selecetedWard = $($.configGlobal.cbWardSearch).val();
	// Get places following by above selected district & ward
	$.ajax({
		url: $.configGlobal.urlGetResultSearchAPI.format(selectedDistrict, selecetedWard),
		type: $.configGlobal.protoGET,
		dataType: $.configGlobal.dataJSON,
		contentType: $.configGlobal.ctnJSON,
		success: function (data) {
			if (data == null) {
				console.log("returned data from ward search api is empty !");
				return;
			}
			//Assign list motels to global            
			$.configGlobal.motels = data;
			// Clear markers on map
			clearAllMarkers();
			// Generate map
			LoadMaps();
		},
		error: function (request, status, msg) {
			console.log(msg);
		}
	});
}
//******************************************
// Declare function to delete address
//******************************************
function markerDeleteOnClick() {
	// Get selected motel
	var selectedId = $(this).attr('title');
	// Confirm user
	var userAction = confirm("Do you want delete motel {0} ?".format(selectedId));
	// If user confirm not delete
	if (userAction == false) {
		return;
	}
	// Call api
	$.ajax({
		url: $.configGlobal.urlDeleteMotelsAPI.format(selectedId),
		type: $.configGlobal.protoDELETE,
		dataType: $.configGlobal.dataJSON,
		contentType: $.configGlobal.ctnJSON,
		success: function (data) {
			if (data == null) {
				console.log("returned data from delete motel api is empty !");
				return;
			}
			refreshMapWithCurrentComboBox();
		},
		error: function (request, status, msg) {
			console.log(msg);
		}
	});
	return false;
}
//******************************************
// Declare function to update address
//******************************************
function markerUpdateOnClick() {
	// Get selected motel
	var selectedId = $(this).attr('title');
	// Confirm user
	var userAction = confirm("Do you want update motel {0} ?".format(selectedId));
	// If user confirm not update
	if (userAction == false) {
		return;
	}
	var currentMarker = $.configGlobal.currentMarker;
	if (!(currentMarker instanceof Array)) {
		console.log("Current marker not selected ");
		return;
	}
	var divTableParent = $(this).parent().parent().parent();
	// var latVal = divTableParent.find('#txtLat').val();
	// var logVal = divTableParent.find('#txtLog').val();
	var latVal = currentMarker[0];
	var logVal = currentMarker[1];
	// console.log("lat: {0} - long:{1}".format(latVal, logVal));   	
	// Prepare object to send
	var addressData = {
		MaDiaChi: selectedId,
		KinhDo: logVal,
		ViDo: latVal
	};
	// Call api and waiting response
	$.ajax({
		url: $.configGlobal.uriGetMotelsAPI,
		type: $.configGlobal.protoPUT,
		dataType: $.configGlobal.dataJSON,
		contentType: $.configGlobal.ctnJSON,
		data: JSON.stringify(addressData),
		cache: false,
		async: false,
		success: function (response) {
			if (response == null) {
				console.log("returned data from update address api is empty !");
				return;
			}
			// Reload map
			refreshMapWithCurrentComboBox();
		},
		error: function (request, status, msg) {
			console.log(msg);
		}
	});
	// Refresh current marker
	$.configGlobal.currentMarker = "";
}
//******************************************
// Declare function to save address
//******************************************
function btnSaveOnClick() {
	// Get all information of saving address
	var soNha = $('#txtNumAddress').val(),
	tenDuong = $('#txtRoadAddress').val(),
	quan = $('#cbDistrictAddress').val(),
	phuong = $('#cbWardAddress').val(),
	viDo = $('#txtLatAddress').val(),
	kinhDo = $('#txtLogAddress').val(),
	tinhTrang = $.configGlobal.visibleStatus
	// Prepare object to send
	addressData = {
		SoNha: soNha,
		TenDuong: tenDuong,
		MaPhuong: phuong,
		MaQuan: quan,
		TinhTrang: tinhTrang,
		KinhDo: kinhDo,
		ViDo: viDo
	};
	// Call api and waiting response
	$.ajax({
		url: $.configGlobal.uriGetMotelsAPI,
		type: $.configGlobal.protoPOST,
		dataType: $.configGlobal.dataJSON,
		contentType: $.configGlobal.ctnJSON,
		data: JSON.stringify(addressData),
		cache: false,
		async: false,
		success: function (response) {
			if (response == null) {
				console.log("returned data from insert new address api is empty !");
				return;
			}
			$($.configGlobal.msgAddResponse).html(response);
			// Reload map
			RetrievePlaces();
		},
		error: function (request, status, msg) {
			console.log(msg);
		}
	});
}
//******************************************
// Declare function to load data in ward comboBox in add form
//******************************************
function loadWardsToAddComboBox() {
	var tempWards = $.configGlobal.wardsAdd;
	// Check type of motels global is none array
	if (!(tempWards instanceof Array)) {
		console.log("wards add variable none array types");
		return;
	}
	var tempSizeOfWards = tempWards.length;
	// Get combobox  add form
	var tempWardAddCombo = $($.configGlobal.cbWardAdd);
	clearOptionFromComboBox(tempWardAddCombo);
	if (tempSizeOfWards < 1) {
		console.log("wards variable is empty");
		return;
	}
	// Each item in ward 
	for (var i = 0; i < tempSizeOfWards; i++) {
		var tempWard = tempWards[i];
		tempWardAddCombo.append("<option value='{0}'>{1}</option>".format(tempWard.MaPhuong, tempWard.TenPhuong));
		tempWard = null;
	}
}
//******************************************
// Declare function to implement selected index changing for district comboBox in add form
//******************************************
function cbDistrictAddSelectedIndexChanging() {
	var selectedDistrict = $($.configGlobal.cbDistrictAdd).val();
	// Call ajax to motel api
	$.ajax({
		url: $.configGlobal.urtGetWardsAPI.format(selectedDistrict),
		type: $.configGlobal.protoGET,
		dataType: $.configGlobal.dataJSON,
		contentType: $.configGlobal.ctnJSON,
		success: function (data) {
			if (data == null) {
				console.log("returned data from ward add api is empty !");
				return;
			}
			// Assign list motels to global
			$.configGlobal.wardsAdd = data;
			// Binding comboBoxes
			loadWardsToAddComboBox();
		},
		error: function (request, status, msg) {
			console.log(msg);
		}
	});
}
//******************************************
// Declare function to add new marker
//******************************************
function addNewMarker() {
	var menu = $.configGlobal.menuContext;
	// Get current point 
	var currentPoint = $.configGlobal.currentPointer;
	if (!(currentPoint instanceof Array)) {
		console.log("current point none array types");
		return;
	}
	var lat = currentPoint[0];
	var lng = currentPoint[1];
	// Close menu context    
	menu.close();
	// Clear text GUI
	$('#txtNumAddress').val('');
	$('#txtRoadAddress').val('');
	$($.configGlobal.msgAddResponse).html('');
	// Binding value to GUI
	$('#txtLatAddress').val(lat);
	$('#txtLogAddress').val(lng);
	// Fire box add new address
	$('.fancybox').fancybox().trigger('click');
}
//******************************************
// Declare function to clear markers on map
//******************************************
function clearAllMarkers() {
	var $map = $.configGlobal.mapObject;
	$map.gmap3({ action: 'clear', name: 'marker' });
}
//******************************************
// Declare function to search places following by district, ward
//******************************************
function btnSearchClick() {
	var selectedDistrict = $($.configGlobal.cbDistrictSearch).val();
	var selecetedWard = $($.configGlobal.cbWardSearch).val();
	// Call ajax to motel api
	$.ajax({
		url: $.configGlobal.urlGetResultSearchAPI.format(selectedDistrict, selecetedWard),
		type: $.configGlobal.protoGET,
		dataType: $.configGlobal.dataJSON,
		contentType: $.configGlobal.ctnJSON,
		success: function (data) {
			if (data == null) {
				console.log("returned data from ward search api is empty !");
				return;
			}
			//Assign list motels to global            
			$.configGlobal.motels = data;
			// Clear markers on map
			clearAllMarkers();
			// Generate map
			LoadMaps();
		},
		error: function (request, status, msg) {
			console.log(msg);
		}
	});
}
//******************************************
// Declare function to clear selected row to comboBoxes
//******************************************
function clearOptionFromComboBox(objComboBox) {
	var tempComboBox = objComboBox;
	var countOptions = tempComboBox.find('option').length;
	// None clear if comboBox empty
	if (countOptions < 1) {
		return;
	}
	// Clear options in comboBox
	tempComboBox
	.find('option')
	.remove()
	.end();
}
//******************************************
// Declare function to load ward to comboBoxes
//******************************************
function loadWardsToSearchComboBox() {
	var tempWards = $.configGlobal.wardsSearch;
	// Check type of motels global is none array
	if (!(tempWards instanceof Array)) {
		console.log("wards search variable none array types");
		return;
	}
	var tempSizeOfWards = tempWards.length;
	// Get combobox  search form        
	var tempWardSearchCombo = $($.configGlobal.cbWardSearch);
	clearOptionFromComboBox(tempWardSearchCombo);
	if (tempSizeOfWards < 1) {
		console.log("wards search variable is empty");
		return;
	}
	// Each item in ward 
	for (var i = 0; i < tempSizeOfWards; i++) {
		var tempWard = tempWards[i];
		tempWardSearchCombo.append("<option value='{0}'>{1}</option>".format(tempWard.MaPhuong, tempWard.TenPhuong));
		tempWard = null;
	}
}
//******************************************
// Declare function to handle selected index changing event 's district search comboBox
//******************************************
function cbDistrictSearchSelectedIndexChanging() {
	var selectedDistrict = $($.configGlobal.cbDistrictSearch).val();
	// Call ajax to motel api
	$.ajax({
		url: $.configGlobal.urtGetWardsAPI.format(selectedDistrict),
		type: $.configGlobal.protoGET,
		dataType: $.configGlobal.dataJSON,
		contentType: $.configGlobal.ctnJSON,
		success: function (data) {
			if (data == null) {
				console.log("returned data from ward search api is empty !");
				return;
			}
			// Assign list motels to global
			$.configGlobal.wardsSearch = data;
			// Binding comboBoxes
			loadWardsToSearchComboBox();
		},
		error: function (request, status, msg) {
			console.log(msg);
		}
	});
}
//******************************************
// Declare function to binding ward to combobox add form
//******************************************
function getDistrictsComboBoxes() {
	// Call ajax to motel api
	$.ajax({
		url: $.configGlobal.urtGetDistrictsAPI,
		type: $.configGlobal.protoGET,
		dataType: $.configGlobal.dataJSON,
		contentType: $.configGlobal.ctnJSON,
		success: function (data) {
			if (data == null) {
				console.log("returned data from districts api is empty !");
				return;
			}
			// Assign list motels to global
			$.configGlobal.districts = data;
			// Binding comboBoxes
			var tempDistricts = $.configGlobal.districts;
			// Check type of motels global is none array
			if (!(tempDistricts instanceof Array)) {
				console.log("districts variable none array types");
				return;
			}
			var tempSizeOfDistricts = tempDistricts.length;
			if (tempSizeOfDistricts < 1) {
				console.log("districts variable is empty");
				return;
			}
			// Get combobox  add form
			var tempDistrictAddCombo = $($.configGlobal.cbDistrictAdd);
			var tempDistrictSearchCombo = $($.configGlobal.cbDistrictSearch);
			// Each item in ward 
			for (var i = 0; i < tempSizeOfDistricts; i++) {
				var tempDistrict = tempDistricts[i];
				tempDistrictAddCombo.append("<option value='{0}'>{1}</option>".format(tempDistrict.MaQuan, tempDistrict.TenQuan));
				tempDistrictSearchCombo.append("<option value='{0}'>{1}</option>".format(tempDistrict.MaQuan, tempDistrict.TenQuan));
				tempDistrict = null;
			}
		},
		error: function (request, status, msg) {
			console.log(msg);
		}
	});
}
//******************************************
// Retrieve places
//******************************************
function RetrievePlaces() {
	// Call ajax to motel api
	$.ajax({
		url: $.configGlobal.uriGetMotelsAPI,
		type: $.configGlobal.protoGET,
		dataType: $.configGlobal.dataJSON,
		contentType: $.configGlobal.ctnJSON,
		success: function (data) {
			if (data == null) {
				console.log("returned data from motel api is empty !");
				return;
			}
			// Assign list motels to global
			$.configGlobal.motels = data;
			// Reset index combobox
			// Generate map
			LoadMaps();
		},
		error: function (msg, url, line) {
			console.log(msg);
		}
	});
}
//******************************************
// Function to load map
//******************************************
function LoadMaps() {
	var $map = $.configGlobal.mapObject,
	menu = $.configGlobal.menuContext,
	center = $.configGlobal.defaultLocaltion;
	var tempMotels = $.configGlobal.motels;
	// Check type of motels global is none array
	if (!(tempMotels instanceof Array)) {
		console.log("motels variable none array types");
		return;
	}
	var tempSizeOfMotels = tempMotels.length;
	if (tempSizeOfMotels < 1) {
		console.log("motels variable is empty");
		$.msgBox({
			title: "Motel Maps",
			content: "Không tìm thấy địa điểm nào trong khu vực này !!"
		});
		return;
	}
	var arrayResult = [];
	// Each item in temp array motel
	for (var i = 0; i < tempSizeOfMotels; i++) {
		var tempLocation = tempMotels[i];
		// var contentInfoWindow = $('.info').html();
		var test = tempLocation.SoNha + " " + tempLocation.TenDuong;
		// contentInfoWindow = contentInfoWindow.format(test, tempLocation.KinhDo,
		// tempLocation.ViDo, tempLocation.MaDiaChi,
		// tempLocation.MaDiaChi, tempLocation.MaDiaChi);
		var itemMarker = { tag: tempLocation.MaDiaChi, lat: tempLocation.KinhDo, lng: tempLocation.ViDo, data: tempLocation };
		arrayResult.push(itemMarker);
		tempLocation = null;
	}
	center = [tempMotels[0].KinhDo, tempMotels[0].ViDo];
	$map.gmap3(
	{// Declare init function
		action: 'init',
		options: { center: center, zoom: 15 },
		events: {
			rightclick: function (map, event) {
				currentPointer = event;
				// Get current pointer from maps
				var position = currentPointer.latLng,
				lat = position.lat(),
				lng = position.lng();
				$.configGlobal.currentPointer = [lat, lng];
				// Open maps
				menu.open(currentPointer);
			},
			click: function () {
				menu.close();
			},
			dragstart: function () {
				menu.close();
			},
			zoom_changed: function () {
				menu.close();
			}
		}
	},
	{
		action: 'addMarkers',
		markers: arrayResult,
		marker: {
			options: {
				draggable: true
			},
			events: {
				dragend: function (marker) {
					var position = marker.getPosition();
					var lat = position.lat(),
					lng = position.lng();
					$.configGlobal.currentMarker = [lat, lng];
					$('#txtLat').val(lat);
					$('#txtLog').val(lng);
				},
				mouseover: function (marker, event, data) {
					var map = $(this).gmap3('get'),
					tempLocation = data,
					contentInfoWindow = $('.info').html(),
					test = tempLocation.SoNha + " " + tempLocation.TenDuong,
					infowindow = $(this).gmap3({ action: 'get', name: 'infowindow' });
					
					contentInfoWindow = contentInfoWindow.format(test, tempLocation.KinhDo,
					tempLocation.ViDo, tempLocation.MaDiaChi,
					tempLocation.MaDiaChi, tempLocation.MaDiaChi);
					
					if (infowindow) {
						infowindow.setContent(contentInfoWindow);
						infowindow.open(map, marker);
		                } else {
						$(this).gmap3({ action: 'addinfowindow',
							anchor: marker,
							infowindow: {
								events: {
									domready: function () {
										// whatever you want to do once the DOM is ready
										$('#delMarker').click(markerDeleteOnClick);
										$('#upMarker').click(markerUpdateOnClick);
									}
								}
							},
							options: { content: contentInfoWindow }
						});
					}
				},
				mouseout: function () {
					//   var infowindow = $(this).gmap3({ action: 'get', name: 'infowindow' });
					//   if (infowindow) {
					//     infowindow.close();
					//   }
				},
				click: function (marker, event, data) {
					var d = data
					title = data.SoNha + " " + data.TenDuong,
					contentWindow = $('.infoLeft').html(),
					leftMenu = $.configGlobal.divLeftMenu;
					contentWindow = contentWindow.format(title, data.KinhDo,
					data.ViDo, data.MaDiaChi);
					$(leftMenu).html(contentWindow);
					// Implement event for btnClearLeftMenu
					$($.configGlobal.btnClearLeftMenu).click(btnClearLeftMenuOnClick);
				}
			}
		}
	}
	);
	$.configGlobal.defaultLocaltion = center;
	$.configGlobal.mapObject = $map;
}		